<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddpage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- table表格区域 -->
      <el-table :data="goodslist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column label="商品价格(元)" prop="goods_price" width="95px"></el-table-column>
        <el-table-column label="商品重量" prop="goods_weight" width="70px"></el-table-column>
        <el-table-column label="创建时间" prop="add_time" width="140px">
          <template slot-scope="scope">
            {{scope.row.add_time | dateFormat}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditGood(scope.row.goods_id)"></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row.goods_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>
    </el-card>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改商品信息" :visible.sync="editDialogVisible" width="30%" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="editForm.goods_price"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input v-model="editForm.goods_number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="editForm.goods_weight"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍" prop="goods_introduce">
          <el-input v-model="editForm.goods_introduce"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="pics">
          <!-- action 表示图片要上传到的后台API地址 -->
          <el-upload
            :action="uploadURL"
            list-type="picture"
            :headers="headerObj"
            :file-list="picsUrlObj"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品的参数" prop="attrs">
          <el-tag v-for="(item,index) in editForm.attrs" :key="index">{{item.attr_value}}</el-tag>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 商品列表
      goodslist: [],
      // 总数据条数
      total: 0,
      // 通过id查询到的商品信息
      editForm: {},
      // 显示或隐藏编辑对话框
      editDialogVisible: false,
      // 修改表单的验证规则对象
      editFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ]
      },
      // 上传图片的URL地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 本地服务器地址
      localHS: 'http://127.0.0.1:8888/'
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 根据分页获取对应的商品列表
    async getGoodsList() {
      const { data: res } = await this.$http.get('goods', {
        params: this.queryInfo
      })

      if (res.meta.status !== 200) {
        return this.$Message.error('获取商品列表失败！')
      }

      // this.$Message.success('获取商品列表成功！')
      // console.log(res.data)
      this.goodslist = res.data.goods
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    async removeById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$Message.info('已经取消删除！')
      }

      const { data: res } = await this.$http.delete(`goods/${id}`)

      if (res.meta.status !== 200) {
        return this.$Message.error('删除失败！')
      }

      this.$Message.success('删除成功！')
      this.getGoodsList()
    },
    goAddpage() {
      this.$router.push('/goods/add')
    },
    // 展示编辑商品的对话框
    async showEditGood(id) {
      const { data: res } = await this.$http.get('goods/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$Message.error('查询商品信息失败！')
      }
      console.log(res.data)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 处理移除图片的操作
    handleRemove(response) {
      console.log(response)
      // 1. 获取将要删除的图片的临时路径
      const filePath = response.url
      // 2. 从 pics 数组中，找到这个图片对应的索引值
      const i = this.editForm.pics.findIndex(x => x.url === filePath)
      // 3. 调用数组的 splice 方法，把图片信息对象，从 pics 数组中移除
      this.editForm.pics.splice(i, 1)
      console.log(this.editForm)
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      // console.log(response)
      // 1. 拼接得到一个图片信息对象
      // const picInfo = { goods_id: this.editForm.goods_id, url: response.data.url }
      const picInfo = { pic: response.data.tmp_path }
      // 2. 将图片信息对象，push 到pics数组中
      this.editForm.pics.push(picInfo)
      console.log(this.editForm)
    },
    // 关闭编辑商品信息对话框
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改后的商品信息
    editUser() {
      console.log(this.editForm)
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起修改好了的用户的网络请求
        console.log(this.editForm)
        const { data: res } = await this.$http.put(
          'goods/' + this.editForm.goods_id,
          this.editForm
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$Message.error('修改用户失败！')
        }
        this.$Message.success('修改用户成功！')
        // 隐藏添加用户的对话框
        this.editDialogVisible = false
        // 重新获取用户列表数据
        this.getGoodsList()
      })
    }
  },
  computed: {
    // 对修改商品信息的图片数组进行处理
    picsUrlObj() {
      const editForm = this.editForm
      if (Object.keys(editForm).length === 0) {
        return editForm
      }
      const pics = editForm.pics
      const picArr = []
      if (pics.length) {
        pics.forEach(element => {
          // const picInfo = { goods_id: element.goods_id, url: Object.prototype.hasOwnProperty.call(element, element.url) ? element.url : element.pics_sma_url }
          let picInfo = {}
          // console.log(element.pic)
          // console.log(typeof element)
          // alert(Object.prototype.hasOwnProperty.call(element, 'pic'))
          if (Object.prototype.hasOwnProperty.call(element, 'pic')) {
            // alert('1111')
            picInfo = { url: this.localHS + element.pic, pics_sma_url: this.localHS + element.pic }
          } else {
            picInfo = { url: element.pics_sma_url, pics_sma_url: element.pics_sma_url }
          }
          picArr.push(picInfo)
        })
        console.log(picArr)
        return picArr
      }
      return picArr
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
  text-align: left;
}
.el-row,
.el-table {
  margin-bottom: 10px;
}
</style>
